import { AICore } from "./AICore";
import fs from 'fs'
import { addLog } from "./Imagen";

export interface IAIMemory{
    id?:number;
    type:'asset'|'file'|'message'
    owner:'user'|'ai'
    //如果资源则是uuid，否则就是绝对路径
    memory:string;
    name?:string;
    desc?:string;
    createTime?:Date;
    modifyTime?:Date;
    longmem?:boolean;
    editobjname?:string;
}

var memid=0;
export class AIMemory implements IAIMemory{
    id=memid++;
    type: "asset" | "file" | "message";
    owner: "user" | "ai";
    memory: string;
    //如果类型是文件，这里保存实际的文件名。如果是uuid，要先转成实际文件，这样会后续带来方便，例如避免异步
    file:string;
    name?: string;
    desc?: string;
    createTime: Date;
    modifyTime?: Date;
    editobjname?:string;
    //是否长期记忆。例如任务界面就不用长期记忆
    longmem=true;
    constructor(initdata:IAIMemory){
        this.type=initdata.type;
        this.owner=initdata.owner;
        this.memory=initdata.memory;
        this.longmem = initdata.longmem??true;
        this.editobjname = initdata.editobjname??undefined;
        this.createTime = new Date();
    }
}


export class AIMemoryManager{
    mems:AIMemory[]=[];
    memdir:string;
    maxmem=200;
    constructor(ai:AICore, maxmem=200){
        this.maxmem=maxmem;
        let ide = ai.ideAgent;
        let projdir = ide.getProjectDir();
        if(projdir){
            let memdir = this.memdir = Editor.projectPath + '/.layaai/aimem/'
            if (!fs.existsSync(memdir)) {
                fs.mkdirSync(memdir);
            }
            this.load();
        }
    }

    //持久保存
    save(){
        fs.writeFileSync( this.memdir+'mems.json', JSON.stringify(this.mems), {encoding:'utf-8'});
    }
    //从持久保存中恢复
    load(){
        let memfile = this.memdir+'mems.json';
        if (fs.existsSync(memfile)) {
            let memstr = fs.readFileSync(memfile,{encoding:'utf-8'});
            if(memstr){
                let mems = JSON.parse(memstr) as AIMemory[];
                this.mems = mems.filter(item=>item.longmem);//删掉非持久的
                if(this.mems.length>0){
                    memid = this.mems[this.mems.length-1].id+1;
                }
            }
        }
    }

    async addFile(f:File|string, owner:'user'|'ai',name?:string, longmem=true):Promise<AIMemory>{
        let memory='';
        let type:'asset'|'file'|'message'='asset'
        let fpath=memory;
        if(f instanceof File){
            memory = (f as any).path;
            type='file'
            fpath=memory;
        }else{
            memory=f;
            fpath = await this.assetToFile(f);
        }
        let r = new AIMemory({type,memory,owner,longmem});
        r.file = fpath;
        this._addmem(r);
        return r;
    }

    addMessage(m:string,who:'user'|'ai',editobjname:string, longmem=true){
        let r = new AIMemory({memory:m,type:"message",owner:who, longmem,editobjname})
        this._addmem(r);
        return r;
    }

    updateMessage(id:number, msg:string){

    }

    removeMessage(id:number){
        let mems = this.mems;
        for(let i=0,len=mems.length; i<len; i++){
            if(mems[i].id==id){
                this.mems.splice(i,1);
                break;
            }
        }
    }
    
    getCurEditObjName(){
        let mems = this.mems;
        let len = mems.length;
        for(let i=len-1;i>=0; i--){
            if(mems[i].editobjname)
                return mems[i].editobjname;
        }
        return null;
    }

    getCurEditObj(){
        let mems = this.mems;
        let len = mems.length;
        for(let i=len-1;i>=0; i--){
            if(mems[i].editobjname)
                return mems[i];
        }
        return null;
    }    

    private async assetToFile(asset:string){
        if(asset.startsWith('file:///'))return asset.substring('file:///'.length);
        if(asset.includes(':')) return asset;
        if(asset.includes('/')) return asset;
        if(asset.includes('\\')) return asset;
        let assetobj = await Editor.assetDb.getAsset(asset);
        return Editor.assetDb.getFullPath(assetobj);
    }

    //先做成只要用户输入的
    getLastAudioFile(){
        let mems = this.mems;
        let len = mems.length;
        for(let i=len-1;i>=0; i--){
            let cm = mems[i];
            if(cm.type=='file' && cm.owner=='user' && (cm.file.endsWith('.mp3') || cm.file.endsWith('.wav')))
                return cm.file;
        }
        return null;
    }

    getLastImageFile(){
        let mems = this.mems;
        let len = mems.length;
        for(let i=len-1;i>=0; i--){
            let cm = mems[i];
            if(cm.type=='file' && cm.owner=='user' && ((cm.file.endsWith('.png') || cm.file.endsWith('.jpg'))))
                return cm.file;
        }
        return null;
    }

    private _addmem(mem:AIMemory){
        this.mems.push(mem);
        let cnt = this.mems.length;
        if(cnt>this.maxmem){
            this.mems = this.mems.splice(cnt-this.maxmem);
        }
        this.save();
        if(mem.longmem){
            addLog({type:'memory', data:mem}, AICore.inst.ideAgent.getSafeUserData(),null);
        }
    }

    getFile(distToLast:number):AIMemory{
        return null;
    }

    getLastInput(){

    }

    /**
     * 根据名字查找，从后往前查找
     * @param name 
     * @returns 
     */
    getFileByName(name:string):AIMemory{
        return null;
    }

    setFileName(file:IAIMemory, name:string){
        file.name=name;
    }

    /**
     * 列出文件以供选择
     */
    selectFile(){
    }


}